﻿using MahApps.Metro;
using MahApps.Metro.Controls;
using SweetWeather.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml;
using Message = Vito.Csharp.Wpf.Controls;
using System.Text.RegularExpressions;
using Microsoft.Win32;

namespace SweetWeather
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        StartWindow start;
        BackGroundViewModel viewmodel;
        DispatcherTimer dt;
        public MainWindow()
        {
            this.Opacity = 0;
            this.ShowInTaskbar = false;
            InitializeComponent();
            viewmodel = new BackGroundViewModel();
            Thread thread = new Thread(LoadResource);
            thread.Priority = ThreadPriority.Highest;
            thread.Start();

            //设置定时器
            dt = new DispatcherTimer();
            int refreshMin = 60;
            int.TryParse(viewmodel.BackGround.RefreshMin, out refreshMin);
            dt.Interval = TimeSpan.FromMinutes(refreshMin);
            dt.Tick += new EventHandler(DispatcherTimerEvent);//调用函数
            dt.Start();

            start = new StartWindow();
            start.closeTheWindows += start_closeTheWindows;
            start.Show();
        }

        /// <summary>
        /// 定时器
        /// </summary>
        private void DispatcherTimerEvent(object sender, EventArgs e)
        {
            progressLoading.Visibility = Visibility.Visible;
            Thread otherad = new Thread(RefreshWeatherInfo);
            otherad.Priority = ThreadPriority.Highest;
            otherad.Start();
            progressLoading.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private void RefreshWeatherInfo()
        {
            viewmodel.GetWeatherInfoExecute(EnumGetWeatherMothod.RealTime.ToString());
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private void RefreshAllWeatherInfo()
        {
            viewmodel.GetWeatherInfoExecute(EnumGetWeatherMothod.All.ToString());
        }

        /// <summary>
        /// 窗体start关闭之后执行
        /// </summary>
        private void start_closeTheWindows()
        {
            this.Opacity = 1;
            this.ShowInTaskbar = true;
            this.GetIpAddress();
        }

        /// <summary>
        /// 执行加载资源等操作
        /// </summary>
        /// <param name="obj"></param>
        private void LoadResource(object obj)
        {
            //Thread.Sleep(3000);
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate()
            {
                //获取天气信息
                viewmodel.GetWeatherInfoExecute(EnumGetWeatherMothod.All.ToString());
                progressLoading.Visibility = Visibility.Hidden;
                var Dt = DateTime.Now;
                DateTime.TryParse(viewmodel.MoreDayWeather.date_y, out Dt);
                ChinaCalendar china = new ChinaCalendar(Dt);
                var ChinaDt = String.Format("今天是{0} {1} {2}[{3}] {4}月{5}", viewmodel.MoreDayWeather.date_y, viewmodel.MoreDayWeather.week,
                    china.GetChinaYear, china.GetAnimal, china.GetChinaMonth, china.GetChinaDay);
                tblToday.Text = ChinaDt;
                this.DataContext = viewmodel;
                start.Close();
            });
        }

        /// <summary>
        /// 得到IP地址
        /// </summary>
        public void GetIpAddress()
        {
            progressLoading.Visibility = Visibility.Visible;
            var path = System.AppDomain.CurrentDomain.BaseDirectory + "Data\\Appconfig.xml";
            XmlDocument doc = new XmlDocument();
            if (File.Exists(path))
            {
                doc.Load(path);
                XmlNode fatherNode = doc.SelectSingleNode("Config");
                var isFirst = ConfigManager.GetElementInnerText(fatherNode, "IsFirst");
                if (!string.IsNullOrEmpty(isFirst) && bool.Parse(isFirst))
                {
                    var r = Vito.Csharp.Wpf.Controls.MessageBox.Show(this, "首次运行，是否根据IP地址自动获取地区信息？", "提示信息", MessageBoxButton.YesNo);
                    if (r == MessageBoxResult.Yes)
                    {
                        var webaddress = ConfigManager.GetElementInnerText(fatherNode, "IPHttpAddress");
                        if (!string.IsNullOrEmpty(webaddress))
                        {
                            var splitAddress = webaddress.Split('|');
                            string[] ipInfo;
                            try
                            {
                                ipInfo = IPManager.GetNetWorkIpAddressByPCOnline(splitAddress[0]);

                                if (ipInfo == null || string.IsNullOrEmpty(ipInfo[0]))
                                {
                                    ipInfo = IPManager.GetNetWorkIpAddressBySina(splitAddress[1]);
                                }
                            }
                            catch (Exception)
                            {
                                ipInfo = IPManager.GetNetWorkIpAddressBySina(splitAddress[1]);
                            }

                            var message = string.Format("您的详细地址为：[{0} {1}] 确认加载此地区？", ipInfo[0], ipInfo[1]);
                            var result = Message.MessageBox.Show(message, "操作提示", MessageBoxButton.YesNo);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (ipInfo.Count() == 2)
                                {
                                    var cityInfo = AreaManager.GetCityInfoByCityName(ipInfo[0].Replace("省", ""), ipInfo[1].Replace("市", ""));
                                    if (cityInfo != null)
                                    {
                                        cityInfo.FullName = ipInfo[0].Replace("省", "") + ipInfo[1].Replace("市", "");
                                        viewmodel.SaveCityMethod(cityInfo);
                                        viewmodel.GetWeatherInfoExecute(EnumGetWeatherMothod.All.ToString());
                                    }
                                }
                            }
                        }
                        else
                        {
                            Message.MessageBox.Show("配置文件出错，请重新安装", "操作提示");
                        }
                    }
                    ConfigManager.ReplaceElementInnerText(path, "IsFirst", false.ToString());
                }
            }
            else
            {
                //Message.MessageBox.Show("配置文件出错，请重新安装", "操作提示");
                Message.MessageBox.Show("配置文件不存在，请重新安装", "操作提示");
            }
            progressLoading.Visibility = Visibility.Hidden;
        }


        /// <summary>
        /// 取消代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            TabWeatherControl.SelectedIndex = 0;
            viewmodel = new BackGroundViewModel();
            if (viewmodel.BackGround.Themes == "Custom")
                cboImageType.SelectedIndex = 2;
            else if (viewmodel.BackGround.Themes == "ExpandWeather")
                cboImageType.SelectedIndex = 1;
            else if (viewmodel.BackGround.Themes == "Default")
                cboImageType.SelectedIndex = 0;
            Thread otherad = new Thread(RefreshAllWeatherInfo);
            otherad.Priority = ThreadPriority.Highest;
            otherad.Start();
            this.DataContext = viewmodel;
        }

        /// <summary>
        /// 城市代码切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            flyCityList.IsOpen = !flyCityList.IsOpen;
        }

        /// <summary>
        /// 添加城市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShowAddCity_Click(object sender, RoutedEventArgs e)
        {
            flyAddCity.IsOpen = true;
        }

        /// <summary>
        /// 添加保存之后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            City city = null;
            if (cboArea.SelectedValue != null)
                city = cboArea.SelectedValue as City;
            if (city != null && city.Code != "0")
                flyAddCity.IsOpen = false;
        }

        /// <summary>
        /// 弹出切换城市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChange_Click(object sender, RoutedEventArgs e)
        {
            flyCityList.IsOpen = !flyCityList.IsOpen;
        }

        /// <summary>
        /// 打开网页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var str = string.Format("http://www.weather.com.cn/weather/{0}.shtml", viewmodel.BackGround.CurrentCity.Code);
            ConfigManager.OpenWebUrl(str);
        }

        /// <summary>
        /// 应用设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnApply_Click(object sender, RoutedEventArgs e)
        {
            TabWeatherControl.SelectedIndex = 0;
            int refreshMin = 60;
            int.TryParse(viewmodel.BackGround.RefreshMin, out refreshMin);
            dt.Interval = TimeSpan.FromMinutes(refreshMin);

            Thread otherad = new Thread(RefreshAllWeatherInfo);
            otherad.Priority = ThreadPriority.Highest;
            otherad.Start();
        }

        /// <summary>
        /// 保存当前城市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MetroWindow_Closed(object sender, EventArgs e)
        {
            viewmodel.SaveCurrentCityExecute();
        }

        /// <summary>
        /// 关于窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutWindow about = new AboutWindow();
            about.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            about.ShowDialog();
        }
    }
}
